package com.solute.web.commons.header;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.solute.domain.SolutionVO;
import com.solute.web.commons.header.service.HeaderService;
import com.solute.web.commons.header.vo.UploadOneProblemFormVO;

@Controller
@RequestMapping(value="/header")
public class HeaderController {

	private static final Logger logger = LoggerFactory.getLogger(HeaderController.class);
	
	private @Autowired HeaderService service;
	
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView header() {
		logger.info("header opend");
		return new ModelAndView("commons/header");
	}
	
	@RequestMapping(value="/uploadOneProblem", method=RequestMethod.POST)
	public @ResponseBody
	void uploadOneProblem(@ModelAttribute @Valid UploadOneProblemFormVO params, BindingResult result) {
		if(result.hasErrors()) {
			logger.error("errors : {}", result.getAllErrors());
			throw new RuntimeException();
		}
		
		SolutionVO vo = new SolutionVO();
		vo.setProblem(params.getProblem());
		vo.setSolution(params.getSolution());
		vo.setSource(params.getSource());
		vo.setAnswer(params.getAnswer());
		
		service.addSolution(params.getProblemImageFiles(), params.getSolutionImageFiles(), params.getTags(), vo);
	}
	
}
